package com.ayf.payment.game.api.controller.platform;

import cn.hutool.core.util.StrUtil;
import com.ayf.payment.game.api.channel.alipay.service.AliPayService;
import com.ayf.payment.game.api.dto.*;
import com.ayf.payment.game.api.dto.alipay.MerchantAlipayOrderDTO;
import com.ayf.payment.game.api.dto.criteria.*;
import com.ayf.payment.game.api.dto.platform.MerchantAccountQueryDTO;
import com.ayf.payment.game.api.dto.platform.NetConfigDTO;
import com.ayf.payment.game.api.dto.platform.SettleConfigDTO;
import com.ayf.payment.game.api.dto.platform.WxMsgConfigDTO;
import com.ayf.payment.game.api.dto.platform.criteria.MerchantAccountCriteria;
import com.ayf.payment.game.api.dto.platform.criteria.MerchantAccountPageCriteria;
import com.ayf.payment.game.api.entity.*;
import com.ayf.payment.game.api.entity.platform.*;
import com.ayf.payment.game.api.exception.ExcelException;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.service.*;
import com.ayf.payment.game.api.service.platform.*;
import com.ayf.payment.game.api.type.*;
import com.ayf.payment.game.api.utils.Base64;
import com.ayf.payment.game.api.utils.*;
import com.ayf.payment.game.api.wx.MyConstant;
import com.ayf.payment.game.api.wx.WxGatewayConfig;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zh-liang
 * @Date : 2020-03-08 11:31
 */
@RequestMapping("/t/merchant")
@RestController
public class AdminMerchantController {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private MerchantConfigService merchantConfigService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ProxyGroupService proxyGroupService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PartitionService partitionService;

    @Autowired
    private GroupsService groupsService;

    @Autowired
    private SettleConfigService settleConfigService;

    @Autowired
    private NetConfigService netConfigService;

    @Autowired
    private NetRechargeUrlService netRechargeUrlService;

    @Autowired
    private MerchantBankService merchantBankService;

    @Autowired
    private SmsRecordService smsRecordService;

    @Autowired
    private MerchantPermissionService merchantPermissionService;
    @Autowired
    private WxConfigService wxConfigService;
    @Autowired
    private WxAutoReplyConfigService wxAutoReplyConfigService;
    @Autowired
    private MerchantAlipayConfigService merchantAlipayConfigService;
    @Autowired
    private MyConstant myConstant;
    @Resource
    private WxGatewayConfig wxGatewayConfig;

    @Autowired
    private MerchantAlipayOrderService merchantAlipayOrderService;
    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private OrderSplitService orderSplitService;

    @Autowired
    private MerchantSignService merchantSignService;
    @Autowired
    private WxMsgConfigService wxMsgConfigService;

    /**
     * 查询出所有商户
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/selectAll")
    public CommonResult<PageDTO> selectAll(@RequestBody MerchantCriteria merchantCriteria) {
        PageHelper.startPage(merchantCriteria.getPageNum(), merchantCriteria.getPageSize());
        List<MerchantDTO> merchants = merchantService.selectAll(merchantCriteria);
        SettleConfigDTO settleConfig = settleConfigService.getSettleConfig();
        for (MerchantDTO merchant : merchants) {
            if (merchant.getSettleCycleCustom().equals(YesAndNo.NO.name())) {
                merchant.setSettleCycle(settleConfig.getSettleCycle());
            }
            if ("LOWER".equals(merchant.getMerchantType())) {
                ProxyGroup proxyGroup = proxyGroupService.selectById(merchant.getIdentificationId());
                merchant.setIdentification(proxyGroup.getGroupName());
            }
        }
        PageInfo<MerchantDTO> pageInfo = new PageInfo<>(merchants);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询所有商户成功", dto);
    }



    /**
     * 更新商户状态
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/updateStatus")
    public CommonResult updateStatus(@RequestBody MerchantCriteria merchantCriteria) {
        Merchant merchant = new Merchant();
        merchant.setId(merchantCriteria.getId());
        merchant.setStatus(merchantCriteria.getStatus());
        if (merchantService.update(merchant)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新商户状态成功");

        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "更新商户状态失败");
    }

    /**
     * 管理员直接登录商户
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/adminLoginMerchant")
    public CommonResult<Map<String, Object>> adminLoginMerchant(@RequestBody MerchantCriteria merchantCriteria, HttpServletRequest request) {
        String ip = IPUtils.getIp(request);
        Token token = tokenService.createToken(merchantCriteria.getId(), merchantCriteria.getId(), LoginType.FATHER.name(),ip);
        Map<String, Object> result = new HashMap<>(16);
        Merchant merchant = merchantService.find(merchantCriteria.getId());
        if (merchant == null) {
            return new CommonResult<Map<String, Object>>(CommonConstants.RETURN_ERROR, "进入商户后台失败，不存在此商户");
        }
        result.put("accessToken", token.getAccessToken());
        result.put("merchantStatus", merchant.getStatus().name());
        result.put("merchantType", merchant.getMerchantType());
        result.put("loginType", "admin");
        NetConfigDTO netConfig = netConfigService.getNetConfig();
        result.put("domainName", netConfig.getDomainName());
        MerchantPermissionDTO dto = merchantPermissionService.adminList(merchant.getMerchantType());
        result.put("permission", dto);
        result.put("type", LoginType.FATHER.name());
        return new CommonResult<Map<String, Object>>(CommonConstants.RETURN_SUCCESS, "登录成功", result);
    }

    /**
     * 强制下线商户
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/mandatoryLogout")
    public CommonResult<String> mandatoryLogout(@RequestBody MerchantCriteria merchantCriteria) {
        tokenService.deleteToken(merchantCriteria.getId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "退出登录成功", null);
    }

    /**
     * 更新商户类型
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/updateMerchantType")
    public CommonResult updateMerchantType(@RequestBody MerchantCriteria merchantCriteria) {
        if (merchantService.updateMerchantType(merchantCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新商户类型成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "更新商户失败");
    }

    /**
     * 查询出商户基本信息
     *
     * @param criteria
     * @return
     */
    @PostMapping("/selectMerchantInfo")
    public CommonResult<MerchantDTO> selectOne(@RequestBody MerchantCriteria criteria) {
        if (criteria.getId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        Merchant merchant = new Merchant();
        merchant.setId(criteria.getId());
        MerchantDTO dto = merchantService.selectOne(merchant);
        dto.setPhone(dto.getPhone());
        dto.setPrivateKey(null);
        MerchantConfig merchantConfig =  merchantConfigService.selectOne(criteria.getId());
        if (merchantConfig != null){
            dto.setNetName(merchantConfig.getNetName());
            dto.setDomainName(merchantConfig.getDomainName());
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询成功", dto);
    }

    /**
     * 更改费率标识ID
     *
     * @param merchantConfig
     * @return
     */
    @PostMapping("/updateSettleIdentificationId")
    public CommonResult updateSettleIdentificationId(@RequestBody MerchantConfig merchantConfig) {
        if (merchantConfigService.updateSettleIdentificationId(merchantConfig)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新费率信息成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "更新费率信息失败");
    }

    /**
     * 代理下属商户查询
     *
     * @param lower
     * @return
     */
    @PostMapping("/selectAllLower")
    public CommonResult<PageDTO> selectAllLower(@RequestBody LowerMerchantCriteria lower) {
        PageHelper.startPage(lower.getPageNum(), lower.getPageSize());
        List<LowerMerchantDTO> dtoList = merchantService.selectAllLower(lower);
        PageInfo<LowerMerchantDTO> pageInfo = new PageInfo<>(dtoList);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询下属商户成功", dto);
    }

    /**
     * 代理商户订单查询
     *
     * @param orderCriteria
     * @return
     */
    @PostMapping("/orderList")
    public CommonResult<ChargeOrderResponseDTO> selectOrder(@RequestBody OrderInfoCriteria orderCriteria) {
        if (StringUtils.isNotEmpty(orderCriteria.getType()) && orderCriteria.getType().equals("ADMIN_PROXY")) {
            List<Integer> proxyIds = merchantService.selectProxyIds();
            orderCriteria.setProxyIds(proxyIds);
        }
        ChargeOrderResponseDTO dto = orderService.selectOrderList(orderCriteria);
        return new CommonResult<ChargeOrderResponseDTO>(CommonConstants.RETURN_SUCCESS, "查询成功", dto);
    }

    /**
     * 查询商户分区
     *
     * @param selectCriteria
     * @return
     */
    @PostMapping("/partitionList")
    public CommonResult<PageDTO> partitionList(@RequestBody PartitionPageCriteria selectCriteria) {
        PageHelper.startPage(selectCriteria.getPageNum(), selectCriteria.getPageSize());
        List<PartitionDTO> partitionDTOS = partitionService.selectByPage(selectCriteria);
        PageInfo<PartitionDTO> pageInfo = new PageInfo<>(partitionDTOS);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询商户分区成功", dto);
    }

    /**
     * 批量删除订单
     * @param criteria
     * @return
     */
    @PostMapping("/delOrders")
    public CommonResult delOrders(@RequestBody OrderCriteria criteria) {
        if (criteria == null) {
            throw new ParameterException("参数不能为空");
        }
        if (null == criteria.getMerchantOrderNos() || 0 == criteria.getMerchantOrderNos().length) {
            throw new ParameterException("请选择订单");
        }

        return orderService.deleteOrders(criteria.getMerchantOrderNos());
    }

    /**
     * 检测分区
     *
     * @param criteria
     * @return
     */
    @PostMapping("/testingGateway")
    public CommonResult testingGateway(@RequestBody PartitionSelectCriteria criteria) {
        if (StringUtils.isEmpty(criteria.getPartitionId())) {
            throw new ParameterException("分区id不能为空");
        }
        if (criteria.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        return partitionService.testingWateGay(criteria);
    }

    /**
     * 查询分组信息
     *
     * @param criteria
     * @return
     */
    @PostMapping("/groupList")
    public CommonResult<PageDTO> groupList(@RequestBody GroupsSelectCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        criteria.setStatus(Status.ENABLE.name());
        List<GroupsDTO> dtoList = groupsService.selectGroupInfo(criteria);
        PageInfo<GroupsDTO> pageInfo = new PageInfo<>(dtoList);
        String url = "";
        List<NetRechargeUrl> urls = netRechargeUrlService.selectAll();
        if (urls != null && urls.size() > 0) {
            url = urls.get(0).getUrl() + "/gws/checkGroup.html";
        }
        for (GroupsDTO groupsDTO : pageInfo.getList()) {
            groupsDTO.setGroupUrl(url);
        }
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<PageDTO>(CommonConstants.RETURN_SUCCESS, "查询分组信息成功", dto);
    }

    /**
     * 充值统计
     *
     * @param statistics
     * @return
     */
    @PostMapping("/topUpStatistics")
    public CommonResult<StatisticsPageDTO> topUpStatistics(@RequestBody StatisticsCriteria statistics) {
        if (StringUtils.isBlank(statistics.getType())) {
            throw new ParameterException("统计类型不能为空");
        }
        PageHelper.startPage(statistics.getPageNum(), statistics.getPageSize());
        StatisticsPageDTO dto = orderService.topUpStatistics(statistics);
        if (StatisticType.MERCHANTDAILY.name().equals(statistics.getType())) {
            OrderInfoCriteria cri = new OrderInfoCriteria();
            cri.setMerchantId(statistics.getMerchantId());
            cri.setOrderGenerateTimeIndexStart(statistics.getOrderGenerateTimeIndexStart());
            cri.setOrderGenerateTimeIndexEnd(statistics.getOrderGenerateTimeIndexEnd());
            ChargeOrderResponseDTO chargeOrderResponseDTO = orderService.selectSumAmountAndFee(cri);
            dto.setSuccessTotal(chargeOrderResponseDTO.getSuccessTotal());
            dto.setSuccessTotalAmount(chargeOrderResponseDTO.getSuccessTotalAmount());
            dto.setMerchantTotalIncome(chargeOrderResponseDTO.getMerchantTotalIncome());
            dto.setPlatformTotalIncome(chargeOrderResponseDTO.getPlatformTotalIncome());
        } else if (StatisticType.PROXYDAILY.name().equals(statistics.getType())) {
            List<Integer> proxyIds = merchantService.selectProxyIds();
            OrderInfoCriteria cri = new OrderInfoCriteria();
            cri.setProxyIds(proxyIds);
            cri.setProxyId(statistics.getProxyId());
            cri.setOrderGenerateTimeIndexStart(statistics.getOrderGenerateTimeIndexStart());
            cri.setOrderGenerateTimeIndexEnd(statistics.getOrderGenerateTimeIndexEnd());
            ChargeOrderResponseDTO chargeOrderResponseDTO = orderService.selectSumAmountAndFee(cri);
            dto.setSuccessTotal(chargeOrderResponseDTO.getSuccessTotal());
            dto.setSuccessTotalAmount(chargeOrderResponseDTO.getSuccessTotalAmount());
            dto.setProxyTotalIncome(chargeOrderResponseDTO.getProxyTotalIncome());
        } else if (StatisticType.DAILY.name().equals(statistics.getType())) {
            OrderInfoCriteria cri = new OrderInfoCriteria();
            cri.setOrderGenerateTimeIndexStart(statistics.getOrderGenerateTimeIndexStart());
            cri.setOrderGenerateTimeIndexEnd(statistics.getOrderGenerateTimeIndexEnd());
            cri.setOrderStatus(OrderStatus.SUCCESS);
            ChargeOrderResponseDTO chargeOrderResponseDTO = orderService.selectSumAmountAndFee(cri);
            dto.setSuccessTotal(chargeOrderResponseDTO.getSuccessTotal());
            dto.setSuccessTotalAmount(chargeOrderResponseDTO.getSuccessTotalAmount());
            dto.setMerchantTotalIncome(chargeOrderResponseDTO.getMerchantTotalIncome());
            dto.setPlatformTotalIncome(chargeOrderResponseDTO.getPlatformTotalIncome());
        } else if (StatisticType.PARTITION.name().equals(statistics.getType())) {
            ChargeOrderResponseDTO chargeOrderResponseDTO = orderService.partitionStatisticSum(statistics);
            dto.setSuccessTotal(chargeOrderResponseDTO.getSuccessTotal());
            dto.setSuccessTotalAmount(chargeOrderResponseDTO.getSuccessTotalAmount());
            dto.setMerchantTotalIncome(chargeOrderResponseDTO.getMerchantTotalIncome());
            dto.setPlatformTotalIncome(chargeOrderResponseDTO.getPlatformTotalIncome());
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "充值统计查询成功", dto);
    }

    /**
     * 导出
     *
     * @param response
     * @param criteria
     * @throws IOException
     */
    @GetMapping(value = "/export")
    public void QQExport(HttpServletResponse response, ExportCriteria criteria) throws IOException {
        if (StringUtils.isBlank(criteria.getType())) {
            throw new ParameterException("导出类型不能为空");
        }
        String fileName = "";

        OrderSelectCriteria orderSelectCriteria = new OrderSelectCriteria();
        orderSelectCriteria.setOrderStatus(OrderStatus.SUCCESS);
        orderSelectCriteria.setOrderGenerateTimeIndexEnd(Integer.valueOf(criteria.getOrderGenerateTimeIndexEnd().replaceAll("-", "")));
        orderSelectCriteria.setOrderGenerateTimeIndexStart(Integer.valueOf(criteria.getOrderGenerateTimeIndexStart().replaceAll("-", "")));
        List<OrderDTO> list = orderService.selectByDTO(orderSelectCriteria);
        List<List<OrderDTO>> list2 = new ArrayList<>();
        int size = 5000;
        int num = list.size() % size == 0 ? list.size() / size : list.size() / size + 1;
        for (int i = 0; i < num; i++) {
            List<OrderDTO> subList = list.subList(i * size, i == num - 1 ? list.size() : (i + 1) * size);
            list2.add(subList);
        }
        try {
            LinkedHashMap<String, String> fieldName = new LinkedHashMap<>();
            fieldName.put("partitionId", "分区ID");
            fieldName.put("partitionName", "分区名称");
            if (criteria.getType().equals("QQ")) {
                fieldName.put("qq", "QQ");
                fileName = "充值QQ信息导出";
            } else {
                fieldName.put("phone", "手机号");
                fileName = "充值手机号信息导出";
            }

            ExcelUtils.listToExcelZip(list2, fieldName, "充值列表", 65535, size, response,
                    fileName + orderSelectCriteria.getOrderGenerateTimeIndexStart() + "-" + orderSelectCriteria.getOrderGenerateTimeIndexEnd(),
                    null, null, ExportType.QQ);
        } catch (ExcelException e) {
            LogPortal.error("{}导出失败,异常信息是:[{}]", fileName, e.getMessage());
        }
    }

    /**
     * 是否可以导出QQ
     *
     * @param response
     * @param criteria
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/exportQQStatus")
    public CommonResult QQExportStatus(HttpServletResponse response, ExportCriteria criteria) throws IOException {
        if (StringUtils.isBlank(criteria.getType())) {
            throw new ParameterException("导出类型不能为空");
        }
        OrderSelectCriteria orderSelectCriteria = new OrderSelectCriteria();
        orderSelectCriteria.setOrderStatus(OrderStatus.SUCCESS);
        orderSelectCriteria.setOrderGenerateTimeIndexEnd(Integer.valueOf(criteria.getOrderGenerateTimeIndexEnd().replaceAll("-", "")));
        orderSelectCriteria.setOrderGenerateTimeIndexStart(Integer.valueOf(criteria.getOrderGenerateTimeIndexStart().replaceAll("-", "")));
        List<OrderDTO> list = orderService.selectByDTO(orderSelectCriteria);
        if (list == null || list.size() == 0) {
            return new CommonResult(CommonConstants.RETURN_ERROR, "导出数据为空");
        }
        return new CommonResult(CommonConstants.RETURN_SUCCESS, "数据可以导出");
    }

    /**
     * 订单是否可以导出
     *
     * @param orderCriteria
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/orderExportStatus")
    public CommonResult orderExportStatus(OrderInfoCriteria orderCriteria) {
        if (StringUtils.isNotEmpty(orderCriteria.getStartTime())) {
            orderCriteria.setStartTime(DateUtils.stringFormat(orderCriteria.getStartTime(),
                    DateUtils.formatPattern_full_01, DateUtils.formatPattern_full));
        }
        if (StringUtils.isNotEmpty(orderCriteria.getEndTime())) {
            orderCriteria.setEndTime(DateUtils.stringFormat(orderCriteria.getEndTime(),
                    DateUtils.formatPattern_full_01, DateUtils.formatPattern_full));
        }
        if (StringUtils.isBlank(orderCriteria.getType())) {
            throw new ParameterException("导出类型不能为空");
        }
        if (orderCriteria.getType().contains("ADMIN_PROXY")) {
            List<Integer> proxyIds = merchantService.selectProxyIds();
            orderCriteria.setProxyIds(proxyIds);
        }
        List<OrderInfoDTO> list = orderService.orderList(orderCriteria);
        if (list == null || list.size() == 0) {
            return new CommonResult(CommonConstants.RETURN_ERROR, "导出数据为空");
        }
        return new CommonResult(CommonConstants.RETURN_SUCCESS, "数据可以导出");
    }

    /**
     * 订单导出
     *
     * @param response
     * @param orderCriteria
     * @throws IOException
     */
    @GetMapping(value = "/orderExport")
    public void orderExport(HttpServletResponse response, OrderInfoCriteria orderCriteria) throws IOException {
        if (StringUtils.isNotEmpty(orderCriteria.getStartTime())) {
            orderCriteria.setStartTime(DateUtils.stringFormat(orderCriteria.getStartTime(),
                    DateUtils.formatPattern_full_01, DateUtils.formatPattern_full));
        }
        if (StringUtils.isNotEmpty(orderCriteria.getEndTime())) {
            orderCriteria.setEndTime(DateUtils.stringFormat(orderCriteria.getEndTime(),
                    DateUtils.formatPattern_full_01, DateUtils.formatPattern_full));
        }
        if (StringUtils.isBlank(orderCriteria.getType())) {
            throw new ParameterException("导出类型不能为空");
        }
        if (orderCriteria.getType().contains("ADMIN_PROXY")) {
            List<Integer> proxyIds = merchantService.selectProxyIds();
            orderCriteria.setProxyIds(proxyIds);
        }
        ExportType exportType = null;
        List<OrderInfoDTO> list = orderService.orderList(orderCriteria);
        List<List<OrderInfoDTO>> list2 = new ArrayList<>();
        int size = 5000;
        int num = list.size() % size == 0 ? list.size() / size : list.size() / size + 1;
        for (int i = 0; i < num; i++) {
            List<OrderInfoDTO> subList = list.subList(i * size, i == num - 1 ? list.size() : (i + 1) * size);
            list2.add(subList);
        }
        try {
            Map<String, Exchange> exchange = new HashMap<>();
            LinkedHashMap<String, String> fieldName = new LinkedHashMap<>();

            fieldName.put("merchantId", "商户id");
            fieldName.put("merchantOrderNo", "商户订单号");
            fieldName.put("partitionId", "分区ID");
            fieldName.put("partitionName", "分区名称");
            fieldName.put("orderStatus", "订单状态");
            fieldName.put("payTypeName", "充值方式");
            fieldName.put("amount", "充值金额");
            fieldName.put("rechargeNumber", "充值账号");
            fieldName.put("createTime", "充值时间");
            fieldName.put("qq", "QQ");
            fieldName.put("phone", "手机号");
            fieldName.put("merchantIncome", "商户收入");
            fieldName.put("fee", "手续费");
            exchange.put("orderStatus", new Exchange() {
                @Override
                public String exchange(String oldValue) {
                    if (oldValue == null) {
                        return null;
                    }
                    if (oldValue.equals(OrderStatus.PROCESSING.name())) {
                        return "订单处理中";
                    } else if (oldValue.equals(OrderStatus.FAIL.name())) {
                        return "充值失败";
                    }
                    if (oldValue.equals(OrderStatus.SUCCESS.name())) {
                        return "充值成功";
                    }
                    return "exchange";
                }
            });
            exchange.put("createTime", new Exchange() {
                @Override
                public String exchange(String oldValue) {
                    if (StringUtils.isBlank(oldValue)) {
                        return oldValue;
                    }
                    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                    try {
                        return DateUtils.dateToString(dateFormat.parse(oldValue), "yyyy-MM-dd HH:mm:ss");
                    } catch (Exception e) {
                        return null;
                    }

                }
            });
            ChargeOrderResponseDTO dto = orderService.selectSumAmountAndFee(orderCriteria);

            List appendSummaryList = new LinkedList();

            appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getSuccessTotal()));
            appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getSuccessTotalAmount()));
            appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getMerchantTotalIncome()));

            if (orderCriteria.getType().contains("ADMIN")) {
                fieldName.put("proxyIncome", "代理商收入");
                fieldName.put("platformIncome", "平台收入");
//                fieldName.put("channelIncome", "渠道收入");
                fieldName.put("payChannleName", "渠道名称");
                appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getProxyTotalIncome()));
                appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getPlatformTotalIncome()));
//                appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getChannelTotalIncome()));
                exportType = ExportType.ADMIN_ORDER_SELECT;
            } else if (orderCriteria.getType().equals("MERCHANT")) {
                appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getFeeTotalAmount()));
                exportType = ExportType.MERCHANT_ORDER_SELECT;
            } else if (orderCriteria.getType().equals("PROXY")) {
                fieldName.put("proxyIncome", "代理商收入");
                appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getFeeTotalAmount()));
                appendSummaryList.add(new DecimalFormat("#0.00").format(dto.getProxyTotalIncome()));
                exportType = ExportType.PROXY_ORDER_SELECT;
            }

            ExcelUtils.listToExcelZip(list2, fieldName, "充值列表", 65535, size, response,
                    "充值订单导出" + DateUtils.dateToString(new Date(), DateUtils.formatPattern_full_01), appendSummaryList, exchange, exportType);
        } catch (ExcelException e) {
            LogPortal.error("异常信息是:", e);
        }
    }

    /**
     * 清理订单信息、结算记录
     *
     * @param clean
     * @return
     */
    @PostMapping("/clean")
    public CommonResult clean(@RequestBody CleanCriteria clean) {
        if (StringUtils.isNotEmpty(clean.getId())) {
            String[] split = clean.getId().split(",");
            clean.setIds(split);
        }
        orderService.cleanOrderAndSettle(clean);
        return new CommonResult(CommonConstants.RETURN_SUCCESS, "清理订单信息、结算记录成功");
    }

    /**
     * 修改商户结算周期
     *
     * @param settleCycle
     * @return
     */
    @PostMapping("/updateSettleCycle")
    public CommonResult updateSettleCycle(@RequestBody SettleCycleCriteria settleCycle) {
        if (merchantConfigService.updateSettleCycle(settleCycle)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "商户结算周期更改成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "商户结算周期更改失败");
    }

    /**
     * 删除商户
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/delete")
    public CommonResult delete(@RequestBody MerchantCriteria merchantCriteria) {
        if (merchantCriteria.getId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        if (merchantService.deleteMerchant(merchantCriteria.getId())) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "删除商户成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "删除商户失败");
    }

    /**
     * 查询待审核商户
     *
     * @param pageCriteria
     * @return
     */
    @PostMapping("/selectAuditedMerchant")
    public CommonResult<PageDTO> selectAuditedMerchant(@RequestBody PageCriteria pageCriteria) {
        PageHelper.startPage(pageCriteria.getPageNum(), pageCriteria.getPageSize());
        List<AuditedMerchantDTO> auditedMerchantDTOS = merchantService.selectAuditedMerchant();
        PageInfo<AuditedMerchantDTO> pageInfo = new PageInfo<>(auditedMerchantDTOS);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<PageDTO>(CommonConstants.RETURN_SUCCESS, "查询待审核商户成功", dto);
    }

    /**
     * 审核商户
     *
     * @param audited
     * @return
     */
    @PostMapping("/pass")
    public CommonResult pass(@RequestBody AuditedMerchantDTO audited) {
        if (audited.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        Merchant merchant = new Merchant();
        merchant.setId(audited.getMerchantId());
        merchant.setStatus(MerchantStatus.ENABLE);
        if (merchantService.update(merchant)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "商户审核成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "商户审核失败");
    }

    /**
     * 获取充值地址
     *
     * @return
     */
    @GetMapping("/getUrl")
    public CommonResult<String> getUrl() {
        List<NetRechargeUrl> urls = netRechargeUrlService.selectAll();
        if (urls != null && urls.size() > 0) {
            return new CommonResult<String>(CommonConstants.RETURN_SUCCESS, " 获取充值地址成功", urls.get(0).getUrl());
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "获取充值地址失败");
    }

    /**
     * 查询待审核银行卡信息
     *
     * @return
     */
    @PostMapping("/auditList")
    public CommonResult<List<MerchantBank>> auditList() {
        MerchantBankCriteria merchantBankCriteria = new MerchantBankCriteria();
        merchantBankCriteria.setStatus(Status.AUDITED);
        List<MerchantBank> bankList = merchantBankService.selectAuditedList(merchantBankCriteria);
        return new CommonResult<List<MerchantBank>>(CommonConstants.RETURN_SUCCESS, "查询待审核银行卡信息成功", bankList);
    }

    /**
     * 查询待审核银行卡信息
     *
     * @return
     */
    @PostMapping("/auditMerchant")
    public CommonResult<List<MerchantBank>> auditMerchant(@RequestBody MerchantBankCriteria merchantBankCriteria) {
        List<String> list = new ArrayList<>();
        list.add(Status.ENABLE.name());
        list.add(Status.AUDITED.name());
        merchantBankCriteria.setStatusList(list);
        List<MerchantBank> bankList = merchantBankService.selectAuditedList(merchantBankCriteria);
        List<MerchantBank> result = new ArrayList<>();
        if (bankList != null && bankList.size() >= 2) {
            result.add(bankList.get(1));
            result.add(bankList.get(0));
        }
        return new CommonResult<List<MerchantBank>>(CommonConstants.RETURN_SUCCESS, "查询待审核银行卡信息成功", result);
    }

    /**
     * 审核银行卡信息
     *
     * @return
     */
    @PostMapping("/auditBank")
    public CommonResult auditBank(@RequestBody MerchantBankCriteria merchantBankCriteria) {
        if (merchantBankService.updateBankStatus(merchantBankCriteria)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "审核银行卡信息成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "审核银行卡信息失败");
    }

    /**
     * 设置普通商户为下级商户
     *
     * @param lower
     * @return
     */
    @PostMapping("/setLower")
    public CommonResult<PageDTO> setLower(@RequestBody LowerMerchantCriteria lower) {
        if (merchantService.setLower(lower)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "设置普通商户为下级商户成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "设置普通商户为下级商户失败");
    }

    /**
     * 短信列表查询
     *
     * @return
     */
    @PostMapping("/smsList")
    public CommonResult<PageDTO> smsList(@RequestBody SMSSelectCriteria smsCriteria) {
        PageHelper.startPage(smsCriteria.getPageNum(), smsCriteria.getPageSize());
        List<SmsRecord> list = smsRecordService.list(smsCriteria);
        PageInfo<SmsRecord> pageInfo = new PageInfo<>(list);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "短信列表查询成功", dto);
    }

    /**
     * 绑定手机号
     *
     * @param settleConfigCriteria
     * @return
     */
    @PostMapping("/bindMobile")
    public CommonResult bindMobile(@RequestBody SettleConfigCriteria settleConfigCriteria) {
        if (merchantConfigService.updatePayStatus(settleConfigCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "修改成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "修改失败");
    }

    /**
     * 获取支付宝代付的状态
     *
     * @param settleConfigCriteria
     * @return
     */
    @PostMapping("/getAliPayStatus")
    public CommonResult<MerchantAlipayConfigDTO> getAliPayStatus(@RequestBody SettleConfigCriteria settleConfigCriteria) {
        if (settleConfigCriteria.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        MerchantAlipayConfigDTO config = merchantAlipayConfigService.getConfigByMerchantId(settleConfigCriteria.getMerchantId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取成功", config);
    }

    /**
     * 更新结算类型
     *
     * @return
     */
    @PostMapping("/updateSettleType")
    public CommonResult updateSettleType(@RequestBody SettleConfigCriteria settleConfigCriteria) {
        if (merchantConfigService.updateSettleType(settleConfigCriteria)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "更新结算类型成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "更新结算类型失败");
    }

    /**
     * 查询渠道结算信息
     *
     * @return
     */
    @PostMapping("/channelSta")
    public CommonResult<List<ChannelStatisticsDTO>> getChannelStatistic(@RequestBody StatisticsCriteria criteria) {
        List<ChannelStatisticsDTO> dto = orderService.channelStatistic(criteria);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询渠道结算汇总成功", dto);
    }

    /**
     * 充值成功发送网关失败重新发送网关
     *
     * @param criteria
     * @return
     */
    @PostMapping("/retryOrders")
    public CommonResult retryOrders(@RequestBody OrderCriteria criteria) {
        if (criteria == null) {
            throw new ParameterException("参数不能为空");
        }
        if (null == criteria.getMerchantOrderNos() || 0 == criteria.getMerchantOrderNos().length) {
            throw new ParameterException("请选择订单");
        }
        return orderService.retryOrders(criteria.getMerchantOrderNos());
    }

    /**
     * 手动向渠道发起订单查询
     *
     * @param criteria
     * @return
     */
    @PostMapping("/checkPayOrder")
    public CommonResult checkPayOrder(@RequestBody OrderCriteria criteria) {
        if (criteria == null) {
            throw new ParameterException("参数不能为空");
        }
        if (null == criteria.getMerchantOrderNo()) {
            throw new ParameterException("请选择订单");
        }
        return orderService.checkPayOrder(criteria.getMerchantOrderNo());
    }

    /**
     * 微信菜单初始化
     *
     * @return
     */
    @GetMapping("/setWxMenu")
    public CommonResult<List<ChannelStatisticsDTO>> setWxMenu() {
        WxConfig config = wxConfigService.getConfig();
        if (config.getStatus() == 0) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "请先开启微信公众号");
        }
        if (myConstant.setMenu(config)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "微信菜单初始化成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "微信菜单初始化失败");
    }

    /**
     * 获取微信配置信息
     *
     * @return
     */
    @GetMapping("/getWxConfig")
    public CommonResult<WxConfig> getWxConfig() {
        WxConfig config = wxConfigService.getConfig();
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取微信配置信息成功", config);
    }

    /**
     * 更新微信配置信息
     *
     * @return
     */
    @PostMapping("/updateWxConfig")
    public CommonResult<WxConfig> updateWxConfig(@RequestBody WxConfig config) {
        config.setId(1);
        if (wxConfigService.updateConfig(config)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改成功");
        } else {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改失败");
        }
    }

    /**
     * 获取微信自动回复配置信息
     *
     * @return
     */
    @GetMapping("/getWxAutoConfig")
    public CommonResult<List<WxAutoReplyConfig>> getWxAutoConfig() {
        List<WxAutoReplyConfig> list = wxAutoReplyConfigService.getListByConfigId(1);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取微信自动回复配置信息成功", list);
    }

    @PostMapping("/updateMerchantPwd")
    public CommonResult<?> updateMerchantPwd(@RequestBody MerchantDTO dto) {
        if (merchantService.updateMerchantPwd(dto)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "修改失败");
    }

    /**
     * 更新微信自动回复配置信息
     *
     * @return
     */
    @PostMapping("/updateWxAutoConfig")
    public CommonResult<WxConfig> updateWxAutoConfig(@RequestBody WxAutoReplyConfigDTO dto) {
        dto.setConfigId(1);
        wxAutoReplyConfigService.updateWxAutoConfig(dto);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改成功");
    }

    /**
     * 微信菜单初始化
     *
     * @return
     */
    @GetMapping("/setWxMenu2")
    public CommonResult<List<ChannelStatisticsDTO>> setWxMenu2() {
        WxConfig config = wxConfigService.getGameConfig(2);
        if (config.getStatus() == 0) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "请先开启微信公众号");
        }
        if (myConstant.setMenu(config)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "微信菜单初始化成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "微信菜单初始化失败");
    }

    /**
     * 获取微信配置信息
     *
     * @return
     */
    @GetMapping("/getWxConfig2")
    public CommonResult<WxConfig> getWxConfig2() {
        WxConfig config = wxConfigService.getGameConfig(2);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取微信配置信息成功", config);
    }

    /**
     * 更新微信配置信息
     *
     * @return
     */
    @PostMapping("/updateWxConfig2")
    public CommonResult<WxConfig> updateWxConfig2(@RequestBody WxConfig config) {
        config.setId(2);
        if (wxConfigService.updateConfig(config)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改成功");
        } else {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改失败");
        }
    }

    /**
     * 查询GM账户列表记录
     * @param merchantAccountPageCriteria
     * @return
     */
    @PostMapping("/queryMerchantAccountList")
    public CommonResult<MerchantAccountQueryDTO> queryMerchantAccountList(@RequestBody MerchantAccountPageCriteria merchantAccountPageCriteria) {
        MerchantAccountCriteria merchantAccountCriteria =BeanConvertUtils.convert(merchantAccountPageCriteria,MerchantAccountCriteria.class);
        MerchantAccountQueryDTO dto=merchantService.countMerchantAccount(merchantAccountCriteria);
        if(null ==dto){
            dto=new MerchantAccountQueryDTO();
        }
        PageHelper.startPage(merchantAccountPageCriteria.getPageNum(), merchantAccountPageCriteria.getPageSize());
        List<MerchantAccountDTO> list= merchantService.merchantAccountList(merchantAccountPageCriteria);
        PageInfo pageInfo = new PageInfo(list);
        dto.setPageInfo(pageInfo);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询GM账户列表", dto);
    }

    /**
     * 设置平台密保微信公众号菜单
     * @return
     */
    @GetMapping("/setPlatformWxMenu")
    public CommonResult<List<ChannelStatisticsDTO>> setPlatformWxMenu() {
        WxConfig config = wxConfigService.getGameConfig(2);
        if (config.getStatus() == 0 || StringUtils.isEmpty(config.getNetUrl())) {
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "请先配置平台动态密保");
        }
        if (wxGatewayConfig.setMenu3(config)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "平台动态密保微信菜单初始化成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "平台动态密保微信菜单初始化失败");
    }

    /**
     * 查询商户结算费率信息
     */
    @GetMapping("/selectRateInfo")
    public CommonResult<List<SettleRateInfoDTO>> selectRateInfo(@RequestParam("merchantId") Integer merchantId) {
        if (merchantId==null) {
            throw new ParameterException("商户id不能为空");
        }
        List<SettleRateInfoDTO> list = merchantService.selectRateInfo(merchantId);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询商户结算费率信息成功", list);
    }

    /**
     * 更改商户结算产品状态
     */
    @PostMapping("/updateProductStatus")
    public CommonResult<?> updateProductStatus(@RequestBody MerchantSettleRateCustom rateCustom) {
        if (rateCustom.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        if (merchantService.updateProductStatus(rateCustom)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "更改商户结算产品状态成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "更改商户结算产品状态失败");
    }


    /**
     * 查询商户支付宝代付配置信息
     *
     * @param
     * @return
     */
    @GetMapping("/getAliPayConfig")
    public CommonResult<MerchantAlipayConfigDTO> getAliPayConfig() {
        MerchantAlipayConfigDTO config = merchantAlipayConfigService.getConfigByMerchantId(0);
        config.setPublicCertBase64(null);
        config.setRootCertBase64(null);
        config.setAlipayPublicCertBase64(null);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询商户支付宝代付配置信息成功", config);
    }

    /**
     * 证书文件上传
     *
     * @param file 证书文件
     * @param type 证书类型
     * @return
     */
    @PostMapping("/uploadCrt")
    public CommonResult<Object> bathPay(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "type") String type) {
        String traceId = SnowFlakeUtils.getTraceId();
        if (file == null) {
            throw new ParameterException("证书不能为空");
        }
        if (StringUtils.isEmpty(type)) {
            throw new ParameterException("证书类型不能为空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = "";
        if (StringUtils.isNotBlank(fileName)) {
            suffixName = fileName.substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        }
        suffixName = suffixName.toLowerCase();
        if (!"crt".equals(suffixName)) {
            LogPortal.error("{} 上传证书文件失败，文件格式错误，仅支持crt，当前文件格式：{}", traceId,suffixName);
            throw new ParameterException("文件格式错误，仅支持crt格式证书");
        }
        try {
            String base64Str = Base64.encode(file.getBytes());
            MerchantAlipayConfigDTO dto = new MerchantAlipayConfigDTO();
            dto.setMerchantId(0);
            switch (type) {
                case "root":
                    dto.setRootCertName(fileName);
                    dto.setRootCertBase64(base64Str);
                    break;
                case "public":
                    dto.setPublicCertName(fileName);
                    dto.setPublicCertBase64(base64Str);
                    break;
                case "alipay":
                    dto.setAlipayPublicCertName(fileName);
                    dto.setAlipayPublicCertBase64(base64Str);
                    break;
                default:
                    throw new ParameterException("证书类型错误");
            }
            if (merchantAlipayConfigService.updateConfig(dto)) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "上传成功", fileName);
            }
        } catch (Exception e) {
            LogPortal.error("{} 上传证书文件失败,发生[{}]异常，异常内容为[{}]", traceId,e.getClass().getName(), e.getMessage());
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "上传失败");
    }

    /**
     * 更新商户支付宝代付配置信息
     *
     * @param dto
     * @return
     */
    @PostMapping("/updateAliPayConfig")
    public CommonResult<MerchantAlipayConfigDTO> updateAliPayConfig(@RequestBody MerchantAlipayConfigDTO dto) {
        dto.setMerchantId(0);
        dto.setStatus(null);
        if (merchantAlipayConfigService.updateConfig(dto)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "更新商户支付宝代付配置信息成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "更新商户支付宝代付配置信息失败");
    }

    /**
     * 企业支付宝代付订单记录查询
     *
     * @param criteria
     * @return
     */
    @PostMapping("/aliPayList")
    public CommonResult<PageDTO> aliPayList(@RequestBody MerchantAlipayOrderCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<MerchantAlipayOrderDTO> list = merchantAlipayOrderService.list(criteria);
        PageInfo<MerchantAlipayOrderDTO> pageInfo = new PageInfo<>(list);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "企业支付宝付款记录查询成功", dto);
    }

    /**
     * 查询GM微信密保配置列表
     * @param configDTO
     * @return
     */
    @PostMapping("/getGmWxConfigList")
    public CommonResult<?> getGmWxConfigList(@RequestBody WxConfigDTO configDTO) {
        List<WxConfigDTO> gmWxConfigList = wxConfigService.getGmWxConfigList(configDTO);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "微信配置列表记录查询成功",gmWxConfigList);
    }

    /**
     * 删除GM微信密保配置记录
     * @param configDTO
     * @return
     */
    @PostMapping("/delGmWxConfig")
    public CommonResult<?> delGmWxConfig(@RequestBody WxConfigDTO configDTO) {
        wxConfigService.deleteGmWxConfig(configDTO.getId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "GM微信密保配置删除成功",null);
    }

    /**
     * 获取分账明细记录
     * @param orderId
     * @return
     */
    @PostMapping("/getSplitOrderList/{orderId}")
    public CommonResult<?> getSplitOrderList(@PathVariable("orderId")String orderId) {
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询成功",orderSplitService.getOrderSplitsByOrderId(orderId));
    }

    /**
     * 查询出商户签约信息列表
     */
    @PostMapping("/selectSignList")
    public CommonResult<PageDTO> selectSignList(@RequestBody MerchantSignCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<MerchantSignDTO> dtos = merchantSignService.selectSignList(criteria);
        PageInfo<MerchantSignDTO> pageInfo = new PageInfo<>(dtos);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询成功", dto);
    }

    /**
     * 下载签约pdf
     */
    @PostMapping("/downSignPdf")
    public void downSignPdf(@RequestBody MerchantSignCriteria criteria, HttpServletResponse response) {
        if (criteria.getMerchantId() == null) {
            throw new ParameterException("商户id不能为空");
        }
        MerchantSign merSignInfo = merchantSignService.getMerSignInfo(criteria.getMerchantId());
        if (StrUtil.isEmpty(merSignInfo.getContractFileUrl())) {
            throw new ParameterException("商户签约文件不存在");
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("平台协议-" + merSignInfo.getName() + ".pdf", "utf-8"));
            response.setHeader("Cache-Control", "No-cache");
            outputStream = response.getOutputStream();
            byte[] bytes = FtpUtil.downloadXYFile("/pdf",merSignInfo.getContractFileUrl());
            outputStream.write(bytes);
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            LogPortal.error("{}下载商户：{}签约pdf失败，发生：{}异常，异常信息为：{}", e, traceId, criteria.getMerchantId(), e.getClass().getSimpleName(), e.getMessage());
            throw new ParameterException("错误码：" + traceId);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                    String traceId = SnowFlakeUtils.getTraceId();
                    LogPortal.error("{}下载商户：{}签约pdf关闭文件流失败，发生：{}异常，异常信息为：{}", e, traceId, criteria.getMerchantId(), e.getClass().getSimpleName(), e.getMessage());
                }
            }
        }
    }

    /**
     * 删除签约信息
     * @param criteria
     * @return
     */
    @PostMapping("/delSign")
    public CommonResult<PageDTO> delSign(@RequestBody MerchantSignCriteria criteria) {
        merchantSignService.deleteMerchantSign(criteria.getMerchantId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "删除成功",null);
    }

    /**
     * 获取微信公众号模板列表
     * @return
     */
    @GetMapping("/getWxTemplate")
    public CommonResult<List<WxMsgConfig>> getWxTemplate() {
        List<WxMsgConfig> list = wxMsgConfigService.getWxTemplate();
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取微信公众号模板列表成功", list);
    }

    /**
     * 获取微信公众号模板配置信息
     * @return
     */
    @GetMapping("/getWxTemplateConfig")
    public CommonResult<WxMsgConfigDTO> getWxTemplateConfig(@RequestParam(value="id")  String id) {
        WxMsgConfigDTO config = wxMsgConfigService.getWxTemplateConfig(id);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取微信公众号模板配置信息成功", config);
    }

    /**
     * 配置模板设置
     * @return
     */
    @PostMapping("/setWxTemplateConfig")
    public CommonResult<?> setWxTemplateConfig(@RequestBody WxMsgConfigDTO wxMsgConfigDTO) {
        if (wxMsgConfigService.setWxTemplateConfig(wxMsgConfigDTO)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "更新微信公众号模板配置信息成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "更新微信公众号模板配置信息失败");
    }
}
